package top.yaofengqiao.springcloudsimple.auth.biz.domain.security.manager;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.auth.model.valobj.UserType;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model.MultiUserTypeAuthenticationToken;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model.Oauth2AuthenticationToken;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model.RefreshTokenAuthenticationToken;
import top.yaofengqiao.springcloudsimple.common.constant.ResponseCode;
import top.yaofengqiao.springcloudsimple.common.util.AppException;

import javax.annotation.Resource;

/**
 * @author yfq
 * @date 2024/6/6 14:45
 * @description
 */
public class OauthAuthenticationManager implements AuthenticationManager {
    @Resource
    private AuthenticationProvider adminAuthenticationProvider;
    @Resource
    private AuthenticationProvider memberAuthenticationProvider;
    @Resource
    private AuthenticationProvider refreshTokenAuthenticationProvider;
    @Resource
    private AuthenticationProvider oauth2AuthenticationProvider;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 账号密码登录
        if (authentication instanceof MultiUserTypeAuthenticationToken) {
            UserType userType = ((MultiUserTypeAuthenticationToken) authentication).getUserType();
            switch (userType) {
                case ADMIN:
                    return adminAuthenticationProvider.authenticate(authentication);
                case MEMBER:
                    return memberAuthenticationProvider.authenticate(authentication);
            }
        }

        // 刷新token
        if (authentication instanceof RefreshTokenAuthenticationToken) {
            return refreshTokenAuthenticationProvider.authenticate(authentication);
        }

        // 三方授权登录
        if (authentication instanceof Oauth2AuthenticationToken) {
            return oauth2AuthenticationProvider.authenticate(authentication);
        }

        throw new AppException(ResponseCode.LOGIN_MODE_NO_SUPPORT);
    }
}
